package com.farina.cryptobox;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;

import javax.crypto.BadPaddingException;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;

import com.farina.cryptobox.R;

import android.os.Bundle;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.view.Menu;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

public class AccountManager extends Activity {

	private String pwdHash="";
	private String username="";
	public final static String EXTRA_MESSAGE_USN2 = "com.example.myfirstapp.USN2";
	public final static String EXTRA_MESSAGE_PPH = "com.example.myfirstapp.PPH";
	public final static String EXTRA_MESSAGE_INFO = "com.example.myfirstapp.INFO";
	public final static String EXTRA_MESSAGE_TITLE = "com.example.myfirstapp.TITLE";
	static final int DIALOG_DELETE_ACCOUNT_ID = 0;

	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		// Get username and password
		Intent intent = getIntent();
		String usn = intent.getStringExtra(MainActivity.EXTRA_MESSAGE_USN);
		String pwd = intent.getStringExtra(MainActivity.EXTRA_MESSAGE_PWD);
		try {
			this.pwdHash=CryptoFunction.MD5(pwd);
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		this.username=usn;
		// Set the text view as the activity layout
		setContentView(R.layout.account_manager);

		TextView title = (TextView) findViewById(R.id.accName);
		title.setText(usn);

		String buffer=loadAllInstances(pwdHash, cryptMD5(username)+"_titles.txt");
		String[] buffArray2=buffer.split("\n");


		Spinner spinner = (Spinner) findViewById(R.id.list_spinner);
		ArrayAdapter<CharSequence> adapter = new ArrayAdapter<CharSequence>(this, R.layout.spinner_item, buffArray2);
		adapter.setDropDownViewResource(R.layout.spinner_item);
		spinner.setAdapter(adapter);
		buffArray2=null;
		buffer="";
		

	}
	

	@Override
	public void onResume() {
		super.onResume();

		String buffer=loadAllInstances(pwdHash, cryptMD5(username)+"_titles.txt");
		String[] buffArray2=buffer.split("\n");


		Spinner spinner = (Spinner) findViewById(R.id.list_spinner);
		ArrayAdapter<CharSequence> adapter = new ArrayAdapter<CharSequence>(this, android.R.layout.simple_spinner_item, buffArray2);
		adapter.setDropDownViewResource(R.layout.spinner_item);
		spinner.setAdapter(adapter);
		buffArray2=null;
		buffer="";
	}

	protected void onActivityResult(int requestCode, int resultCode,
			Intent data) {
		if (requestCode == 1) {
			if (resultCode == RESULT_OK) {
				String newpwd = data.getStringExtra(Change_Password.EXTRA_MESSAGE_NEWPWD);
				String inst=loadAllInstances(pwdHash, cryptMD5(username)+"_titles.txt");
				writeAllInstances(newpwd, inst, cryptMD5(username)+"_titles.txt");
				inst=loadAllInstances(pwdHash, cryptMD5(username)+"_instances.txt");		
				writeAllInstances(newpwd, inst, cryptMD5(username)+"_instances.txt");
				pwdHash=newpwd;
				Context context = getApplicationContext();
				CharSequence text = "Password Changed!";
				int duration = Toast.LENGTH_SHORT;
				Toast toast = Toast.makeText(context, text, duration);
				toast.show();
			}
		}
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getMenuInflater().inflate(R.menu.activity_display_message, menu);
		return true;
	}
	
	




	public void view(View view) {
		Spinner spinner = (Spinner) findViewById(R.id.list_spinner);
		String title = spinner.getItemAtPosition(spinner.getFirstVisiblePosition()).toString();
		if(title.equals("")){return;}
		Intent intent = new Intent(this, ViewActivity.class);
		intent.putExtra(EXTRA_MESSAGE_USN2, username);
		intent.putExtra(EXTRA_MESSAGE_PPH, pwdHash);
		intent.putExtra(EXTRA_MESSAGE_INFO, "view");
		intent.putExtra(EXTRA_MESSAGE_TITLE, title);
		startActivity(intent);
	}

	public String cryptMD5(String s){
		String usnHash="";
		try {
			usnHash=CryptoFunction.MD5(s);
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		return usnHash;
		
	}

	public void delete(View view) {
		Spinner spinner = (Spinner) findViewById(R.id.list_spinner);
		String title = spinner.getItemAtPosition(spinner.getFirstVisiblePosition()).toString();
		
		
		String buffer=loadAllInstances(pwdHash, cryptMD5(username)+"_instances.txt");		
		String[] buffArray=buffer.split("\n");

		for(int i=0;i<buffArray.length; i++){
			if(buffArray[i].equals("TITLE"+title)){
				buffArray[i]="";
				buffArray[i+2]="";
				buffArray[i+2]="";
				buffArray[i+3]="";
				break;
			}
		}
		buffer="";
		for(int i=0;i<buffArray.length; i++) {
			if(!buffArray[i].equals("")) buffer=buffer+buffArray[i]+"\n";
		}
		writeAllInstances(pwdHash, buffer, cryptMD5(username)+"_instances.txt");

		buffer=loadAllInstances(pwdHash, cryptMD5(username)+"_titles.txt");
		String[] buffArray2=buffer.split("\n");

		for(int i=0;i<buffArray2.length; i++){
			if(buffArray2[i].equals(title)){
				buffArray2[i]="";
				break;
			}
		}
		buffer="";
		for(int i=0;i<buffArray2.length; i++) {
			if(!buffArray2[i].equals("")) buffer=buffer+buffArray2[i]+"\n";
		}
		writeAllInstances(pwdHash, buffer, cryptMD5(username)+"_titles.txt");
		buffArray2=buffer.split("\n");


		ArrayAdapter<CharSequence> adapter = new ArrayAdapter<CharSequence>(this, R.layout.spinner_item, buffArray2);
		adapter.setDropDownViewResource(R.layout.spinner_item);
		spinner.setAdapter(adapter);

		buffer="";
		buffArray2=null;
		buffArray=null;


	}

	public void add(View view) {
		Intent intent = new Intent(this, ViewActivity.class);
		intent.putExtra(EXTRA_MESSAGE_USN2, username);
		intent.putExtra(EXTRA_MESSAGE_PPH, pwdHash);
		intent.putExtra(EXTRA_MESSAGE_INFO, "add");
		startActivity(intent);
	}

	public void changeAccountPwd(View view) {

		Intent intent = new Intent(this, Change_Password.class);
		intent.putExtra(EXTRA_MESSAGE_USN2, username);
		intent.putExtra(EXTRA_MESSAGE_PPH, pwdHash);
		startActivityForResult(intent, 1);

	}

	public String loadAllInstances(String key, String filename) {

		File f = new File(getExternalFilesDir(null), filename);
		FileReader fr = null;
		BufferedReader br = null;
		String buffer="";

		try{
			fr = new FileReader(f);
			br = new BufferedReader(fr);
			while(true){
				String tmp = br.readLine();
				if(tmp==null){br.close(); break;}
				buffer=buffer+tmp;
			}
		}
		catch (IOException e) {      
			e.printStackTrace();
		}

		try {
			buffer=CryptoFunction.AES_Decrypt(buffer, key);
		} catch (InvalidKeyException e) {
			e.printStackTrace();
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		} catch (NoSuchPaddingException e) {
			e.printStackTrace();
		} catch (IllegalBlockSizeException e) {
			e.printStackTrace();
		} catch (BadPaddingException e) {
			e.printStackTrace();
		}

		return buffer;
	}

	public void writeAllInstances(String key, String buffer, String filename) {

		try {
			buffer=CryptoFunction.AES_Encrypt(buffer, key);
		} catch (InvalidKeyException e1) {
			e1.printStackTrace();
		} catch (NoSuchAlgorithmException e1) {
			e1.printStackTrace();
		} catch (NoSuchPaddingException e1) {
			e1.printStackTrace();
		} catch (IllegalBlockSizeException e1) {
			e1.printStackTrace();
		} catch (BadPaddingException e1) {
			e1.printStackTrace();
		}

		File f = new File(getExternalFilesDir(null), filename);
		FileWriter fw = null;
		BufferedWriter bw = null;
		try{
			fw = new FileWriter(f, false);
			bw = new BufferedWriter(fw);
			bw.write(buffer);
			bw.close();
		}
		catch (IOException e) {      
			e.printStackTrace(); 
		}
	}

	public void writFileString(File f, String s){
		FileWriter fw = null;
		BufferedWriter bw = null;
		try{
			fw = new FileWriter(f, false);
			bw = new BufferedWriter(fw);
			bw.write(s);
			bw.close();
		}
		catch (IOException e) {      
			e.printStackTrace(); 
		}

	}


	protected Dialog onCreateDialog(int id) {
		Dialog dialog=null;
		switch(id) {
		case DIALOG_DELETE_ACCOUNT_ID:
			AlertDialog.Builder builder = new AlertDialog.Builder(this);
			builder.setMessage("Are you sure you want delete your Account? All data will be destroyed!")
			.setCancelable(false)
			.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog, int id) {
					deleteAccountSerivce(username);
					File ftitles = new File(getExternalFilesDir(null), cryptMD5(username)+"_titles.txt");
					File finstances = new File(getExternalFilesDir(null), cryptMD5(username)+"_instances.txt");
					ftitles.delete();
					finstances.delete();
					logout();
				}
			})
			.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog, int id) {
					dialog.cancel();
				}
			});
			dialog = builder.create();
			break;
		default:
			dialog = null;
		}
		return dialog;
	}

	public void deleteAccountSerivce(String usn){

		File f = new File(getExternalFilesDir(null), "accounts.txt");
		String fileToS="";
		FileReader fr = null;
		BufferedReader br = null;
		try {
			usn=CryptoFunction.MD5(usn);
		} catch (NoSuchAlgorithmException e1) {
			e1.printStackTrace();
		} catch (UnsupportedEncodingException e1) {
			e1.printStackTrace();
		}
		try{
			fr = new FileReader(f);
			br = new BufferedReader(fr);
			while(true){
				String tmpUsn = br.readLine();
				if(tmpUsn==null)break;
				if(tmpUsn.equals(usn)){br.readLine(); continue;}
				String tmpPwd = br.readLine();
				fileToS=fileToS+tmpUsn+"\n";
				fileToS=fileToS+tmpPwd+"\n";
			}			
			br.close(); 
		}
		catch (IOException e) {      
			e.printStackTrace(); 
		}
		writFileString(f, fileToS);
	}


	public void deleteAccount(View view) {
		
		setResult(RESULT_OK);
		this.showDialog(DIALOG_DELETE_ACCOUNT_ID);
		
	}

	public void logout(View view) {
		this.finish();
	}
	
	public void logout() {
		this.finish();
	}


}
